package mta.io.csv.reader;

import au.com.bytecode.opencsv.CSVReader;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;

/**
 * Created by Dmitry Nikolaev.
 * User: dima
 * Date: 14.01.2009
 * Time: 9:09:09
 */
public class CsvTranslationReader {
    private String filePath;
    private HashMap<String, String> translations;

    public CsvTranslationReader(String filePath) {
        this.filePath = filePath;
    }

    public HashMap<String, String> getPhrases() {
        if (translations != null) {
            return new HashMap<String, String>(translations);
        }

        CSVReader reader;
        try {
            reader = new CSVReader(new FileReader(filePath));
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }

        List<String[]> csvContent;
        try {
            csvContent = reader.readAll();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        translations = new HashMap<String, String>();
        int currentRow = 0;
        for (String[] row : csvContent) {
            if (row.length != 2) {
                throw new RuntimeException("Invalid row " + currentRow + " in " + filePath);
            } else {
                String original = row[0];
                String translation = row[1];
                if (translation.equals(original)) {
                    translations.put(original, null);
                } else {
                    translations.put(original, translation);
                }
            }
            currentRow++;
        }
        return translations;
    }
}
